package com.fliangyun.nsa.nsamanage.controller;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.fliangyun.nsa.nsamanage.constant.CommonConstant;
import com.fliangyun.nsa.nsamanage.dao.CalendarInfoMapper;
import com.fliangyun.nsa.nsamanage.dao.LogInfoMapper;
import com.fliangyun.nsa.nsamanage.dao.UserMapper;
import com.fliangyun.nsa.nsamanage.entities.CalendarInfo;
import com.fliangyun.nsa.nsamanage.entities.LogInfo;
import com.fliangyun.nsa.nsamanage.entities.User;
import com.fliangyun.nsa.nsamanage.service.impl.CalendarInfoServiceImpl;
import com.fliangyun.nsa.nsamanage.service.impl.LogInfoServiceImpl;
import com.fliangyun.nsa.nsamanage.utils.MailUtil;
import com.fliangyun.nsa.nsamanage.utils.SmsUtil;
import com.fliangyun.nsa.nsamanage.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author fuliangyun@139.com
 * @date 2023年06月27日
 * @description
 */
@Slf4j
@Component
public class CronController {

    @Autowired
    private CalendarInfoMapper calendarInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogInfoMapper logInfoMapper;

    /**
     * 每天12点钟发送短信
     * @author fuliangyun@139.com
     * @date 2023-06-27 9:53
     */
    @Scheduled(cron = "0 0 12 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void job(){
        List<CalendarInfo> calendarInfoList = calendarInfoMapper.findList(new CalendarInfo());
//        if (!CollectionUtils.isEmpty(dataList)){
//
//            // 查询用户手机号码
//            User user = new User();
//            user.setSmsFlag(CommonConstant.ONE);
//            List<User> userList = userMapper.findList(user);
//            if (!CollectionUtils.isEmpty(userList)){
//                Map<String, User> mobileMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (o1, o2) -> o1));
//
//                Date nowDate = new Date();
//                try {
//                    nowDate = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//
//                for (CalendarInfo calendarInfo : dataList) {
//                    Calendar birthday = null;
//                    if (CommonConstant.ONE.equals(calendarInfo.getType())){
//                        // 新历
//                        birthday = Calendar.getInstance();
//                        birthday.setTime(calendarInfo.getBirthday());
//                    }else if (CommonConstant.TWO.equals(calendarInfo.getType())){
//                        // 农历
//                        Calendar calendar = Calendar.getInstance();
//                        // 今年年份
//                        int year = calendar.get(Calendar.YEAR);
//                        calendar.setTime(calendarInfo.getBirthday());
//                        // 加载农历
//                        ChineseDate chineseDate = new ChineseDate(year, calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DATE));
//                        // 农历转新历
//                        birthday = Calendar.getInstance();
//                        birthday.setTime(chineseDate.getGregorianDate());
//                    }
//
//                    // 判断两个日期是否是重复
//                    if (birthday != null){
//                        // 设置生日为当前年份
//                        Calendar now = Calendar.getInstance();
//                        birthday.set(Calendar.YEAR, now.get(Calendar.YEAR));
//                        // 判断两个日期是否相同
//                        long days = Math.round((birthday.getTimeInMillis() - nowDate.getTime()) / CommonConstant.DAYS);
////                        log.info("birthday:{}, now:{}", DateFormatUtils.format(birthday, "yyyy-MM-dd HH:mm:ss"), DateFormatUtils.format(nowDate, "yyyy-MM-dd HH:mm:ss"));
////                        log.info("days: {}", days);
//                        User uu = mobileMap.get(calendarInfo.getUserId());
//                        String mobile = uu.getMobile();
//                        if (days == 0 && checkMobile(mobile)){
//                            // 就是同一天
//                            String msg = "{\"name\":\""+calendarInfo.getRemark()+"\"}";
////                            log.info("msg: {}", msg);
//                            SendSmsResponseBody body = null;
//                            try {
//                                body = SmsUtil.sendSms(mobile, msg, uu.getKeyId(), uu.getKeySecret(), uu.getSign(), uu.getTemplateCode());
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
////                            log.info("body: {}", JSON.toJSONString(body));
//                            if (body != null && CommonConstant.OK.equals(body.getCode())){
//                                LogInfo logInfo = new LogInfo();
//                                Map<String, Object> map = new HashMap<>();
//                                map.put("mobile", mobile);
//                                map.put("msg", msg);
//                                map.put("status", "发送成功");
//                                map.put("body", body);
//                                logInfo.setDetail(JSON.toJSONString(map));
//                                logInfo.setAction("发送短信");
//                                logInfo.setId(StringUtil.uuid());
//                                logInfo.setCreateTime(new Date());
//                                logInfoMapper.insert(logInfo);
//                            }
//                        }
//                    }
//                }
//            }
//        }

//        List<CalendarInfo> calendarInfoList = calendarInfoService.findList(new CalendarInfo(), authentication);
        if (!CollectionUtils.isEmpty(calendarInfoList)) {
            // 检查生日是否已过

            Date nowDate = new Date();
            try {
                nowDate = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }

            for (CalendarInfo calendarInfo : calendarInfoList) {
                if (CommonConstant.ONE.equals(calendarInfo.getType())){
                    // 新历
                    calendarInfo.setType("新历");
                    Calendar calendar = Calendar.getInstance();
                    Calendar birthday = Calendar.getInstance();
                    birthday.setTime(calendarInfo.getBirthday());
                    calendarInfo.setAge(calendar.get(Calendar.YEAR)-birthday.get(Calendar.YEAR));
                    // 设置当前年份
                    birthday.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
//                    calendarInfo.setDays((int) DateUtil.between(nowDate, birthday.getTime(), DateUnit.DAY));
                    calendarInfo.setDays(Math.round((birthday.getTimeInMillis() - nowDate.getTime()) / CommonConstant.DAYS));
                    if (calendarInfo.getDays() != 0){
                        if ((nowDate.getTime()-birthday.getTimeInMillis()) > 0){
                            calendarInfo.setPassFlag(true);
                            calendarInfo.setDays(9999L);
                        }else {
                            calendarInfo.setAge(calendarInfo.getAge()-1);
                        }
                    }
                    calendarInfo.setBirthdayLabel(DateFormatUtils.format(calendarInfo.getBirthday(), "yyyy年MM月dd日"));

                }else if (CommonConstant.TWO.equals(calendarInfo.getType())){
                    // 农历
                    ChineseDate now = new ChineseDate(new Date());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(calendarInfo.getBirthday());
                    // 组装
                    ChineseDate date = new ChineseDate(now.getChineseYear(), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DATE));
                    calendarInfo.setAge(now.getChineseYear()-calendar.get(Calendar.YEAR));
                    Date birthday = date.getGregorianCalendar().getTime();
                    calendarInfo.setDays(Math.round((birthday.getTime() - nowDate.getTime()) / CommonConstant.DAYS));
                    if (calendarInfo.getDays() != 0){
                        if ((nowDate.getTime()-birthday.getTime()) > 0){
                            calendarInfo.setPassFlag(true);
                            calendarInfo.setDays(9999L);
                        }else {
                            calendarInfo.setAge(calendarInfo.getAge()-1);
                        }
                    }
                    // 组装
                    ChineseDate dd = new ChineseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DATE));
                    calendarInfo.setBirthdayLabel(String.format("%s年%s%s", calendar.get(Calendar.YEAR), dd.getChineseMonth(), dd.getChineseDay()));
                    calendarInfo.setType("农历");
                }
            }
        }

        // 排序，按照最近生日排序
        calendarInfoList = calendarInfoList.stream().sorted(Comparator.comparing(CalendarInfo::getDays)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(calendarInfoList)){
            User user = new User();
            user.setSmsFlag(CommonConstant.ONE);
            List<User> userList = userMapper.findList(user);
            if (!CollectionUtils.isEmpty(userList)) {
                Map<String, User> mobileMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (o1, o2) -> o1));
                for (CalendarInfo calendarInfo : calendarInfoList) {
                    User uu = mobileMap.get(calendarInfo.getUserId());
                    String mail = uu.getMail();
                    if (calendarInfo.getDays() == 0 && StringUtil.isNotBlank(mail)) {
                        // 就是同一天
                        String msg = String.format("今天是【%s】的生日", calendarInfo.getRemark());
//                            log.info("msg: {}", msg);
                        boolean sendFlag = false;
                        try {
                            sendFlag = MailUtil.sendMail(mail, msg, msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//                            log.info("body: {}", JSON.toJSONString(body));
                        if (sendFlag) {
                            LogInfo logInfo = new LogInfo();
                            Map<String, Object> map = new HashMap<>();
                            map.put("mail", mail);
                            map.put("msg", msg);
                            map.put("status", "发送成功");
                            map.put("body", msg);
                            logInfo.setDetail(JSON.toJSONString(map));
                            logInfo.setAction("发送邮件");
                            logInfo.setId(StringUtil.uuid());
                            logInfo.setCreateTime(new Date());
                            logInfoMapper.insert(logInfo);
                        }
                    }
                }

            }
        }

    }

    /**
     * 检查是否是手机号码
     * @author fuliangyun@139.com
     * @date 2023-06-27 11:44
     * @param mobile 手机号码
     * @return boolean
     */
    private boolean checkMobile(String mobile){
        //正则表达式
        String mobileRegEx = "^1[3456789][0-9]{9}$";
        //函数语法 匹配的正则表达式
        Pattern pattern = Pattern.compile(mobileRegEx);
        //进行匹配
        Matcher matcher = pattern.matcher(mobile);
        return matcher.matches();
    }

}
